<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        h2 {
            text-align: center;
        }
        
        .box {
            width: 80%;
            height: 450px;
            border: 2px solid #f00;
            margin: 20px auto;
            font-size: 100px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
    </style>
</head>

<body>
    <h2>JS原生实现防抖</h2>
    <div class="box"></div>
</body>
<script>
    const box = document.querySelector('.box')
    box.addEventListener('mousemove', debounce(fnMove, 2000), false)

    let i = 0;

    function fnMove(e) {
        i++
        this.textContent = i;
    }

    //通过防抖函数限制触发次数-- 实现原理：定时器实现
    function debounce(fn, waiting = 1000) {
        let timer = null;
        return function() {
            //解决this丢失问题
            const _this = this;
            //解决事件对象丢失问题
            const args = arguments
            clearTimeout(timer)
            timer = setTimeout(function() {
                fn.apply(_this, args)
            }, waiting)

        }

    }
</script>

</html>